<template>
  <div>
    <el-form :model="form" label-width="130px" :rules="rules" ref="form" style="margin-top: -12px">
      <el-form-item label="规格信息" class="one-label">

        <!-- 规格类型 -->
        <el-form-item label="规格类型：" label-width="170px" prop="skuFlag">
          <el-radio-group v-model="form.skuFlag" :disabled="!skuChangeFlag" @change="doChangeSkuFlag">
            <template v-for="(val, key) in dict.skuFlag">
              <el-radio :label="key" :key="key">{{ val }}</el-radio>
            </template>
          </el-radio-group>
        </el-form-item>

        <!-- 供货联盟商品 -->
        <template v-if="form.goodsSource === '3'">

          <!-- 供货联盟供应价 -->
          <el-form-item label="供货联盟供应价：" label-width="170px">
            <span>{{ form.supplyAlliancePrice }}元</span>
            <div style="color: #999999">供货联盟商品与分销企业结算的商品价格 </div>
          </el-form-item>

          <!-- 供货联盟运费 -->
          <el-form-item label="供货联盟运费：" label-width="170px">
            <span v-if="form.supplyAlliancePostFee > 0">{{ form.supplyAlliancePostFee }}</span>
            <span v-else>包邮</span>
          </el-form-item>

          <!-- 零售价模式 -->
          <el-form-item label="零售价模式: " label-width="170px" v-if="fromListPage == 30">
            <span v-if="form.supplyAllianceSellPriceType === 1">限定零售价范围</span>
            <span v-else-if="form.supplyAllianceSellPriceType === 2">限定零售价</span>
            <span v-else-if="form.supplyAllianceSellPriceType === 3">不限定零售价</span>
            <span v-else>未设置</span>
            <span v-if="form.supplyAllianceSellMinPrice">
              <span v-if="form.supplyAllianceSellMinPrice  === form.supplyAllianceSellMaxPrice">
                ￥{{form.supplyAllianceSellMinPrice}}
              </span>
              <span v-else>
                <span v-if="form.supplyAllianceSellMaxPrice !== null">
                  ￥{{form.supplyAllianceSellMinPrice}}--{{form.supplyAllianceSellMaxPrice}}
                </span>
              </span>
              <span v-if="form.supplyAllianceSellPriceType === 3">(建议零售价)</span>
            </span>
            <div style="color: #999999">供货联盟商品零售价限定模式</div>
          </el-form-item>

          <!-- 批发价模式 -->
          <el-form-item label="批发价模式: " label-width="170px" v-if="fromListPage == 31">
            <div v-if="form.supplyAllianceIsEnableWholesaleModel === 1">
              <span v-if="form.supplyAllianceWholesalePriceType === 1">限定批发价范围</span>
              <span v-else-if="form.supplyAllianceWholesalePriceType === 2">限定批发价</span>
              <span v-else-if="form.supplyAllianceWholesalePriceType === 3">不限定批发价</span>
              <span v-else>未设置</span>
              <span v-if="form.supplyAllianceMinWholesalePrice">
                <span v-if="form.supplyAllianceMinWholesalePrice  === form.supplyAllianceMaxWholesalePrice">
                  ￥{{form.supplyAllianceMinWholesalePrice}}
                </span>
                <span v-else>
                  <span v-if="form.supplyAllianceMaxWholesalePrice !== null">
                    ￥{{form.supplyAllianceMinWholesalePrice}}--{{form.supplyAllianceMaxWholesalePrice}}
                  </span>
                </span>
                <span v-if="form.supplyAllianceWholesalePriceType === 3">(建议批发价)</span>
              </span>
            </div>
            <div v-else>未设置</div>
            <div style="color: #999999">供货联盟商品批发价限定模式</div>
          </el-form-item>
        </template>

        <!-- 批发商品 -->
        <template v-if="fromListPage == 31">

          <!-- 阶梯批发 -->
          <el-form-item label="阶梯批发：" label-width="170px" prop="ladderAuth">
            <el-switch v-model="form.ladderAuth"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              :disabled="form.supplyAllianceIsEnableWholesaleModel === 1 && form.supplyAllianceWholesalePriceType === 2"
              inactive-value="0">
            </el-switch>
            <a :style="{'font-size': '14px', color:form.ladderPriceList.length > 0 ? '#409eff' : '#999999', 'text-decoration': 'underline !important' }"
              @click="ladderVisible = true"
              v-if="form.ladderAuth == 1"
              v-text="form.ladderPriceList.length > 0 ? '已设置阶梯价' : '未设置阶梯价'">
            </a>
          </el-form-item>

          <!-- 起批数量 -->
          <el-form-item v-if="form.ladderAuth == 0" label="起批数量：" label-width="170px" prop="wholesaleNum">
            <el-input v-model="form.wholesaleNum"
              class="short-input width-per-50"
              @keyup.native="form.wholesaleNum = checkInputPositiveNum(form.wholesaleNum)">
            </el-input>
            <div class="tips">起批数量须大于0，设置后不足起批数量无法下单</div>
          </el-form-item>

        </template>

        <!-- 单规格 -->
        <template v-if="form.skuFlag == 0">

          <!-- 商品条形码 -->
          <el-form-item label="商品条形码：" label-width="170px">
            <el-input v-model.trim="form.goodsBarCode" class="long-input" placeholder="请输入商品条形码" maxlength="100" show-word-limit/>
          </el-form-item>

          <!-- 外部编码 -->
          <el-form-item label="外部编码：" label-width="170px">
            <el-input v-model.trim="form.externalCode" :disabled="form.goodsSource === '3'" class="long-input" placeholder="请输入外部编码" maxlength="100" show-word-limit/>
          </el-form-item>

          <!-- 划线价 -->
          <el-form-item label="划线价：" label-width="170px">
            <el-input v-model="form.scribingPrice"
              @keyup.native="form.scribingPrice = checkInputNum(form.scribingPrice)"
              class="short-input width-per-50">
              <template slot="append">元</template>
            </el-input>
            <div class="tips">划线价在商品详情会以划线形式显示</div>
          </el-form-item>

          <!-- 批发商品 -->
          <!-- <template v-if="fromListPage == 31"> -->
          <div v-if="fromListPage == 31">
            <!-- 批发价 -->
            <el-form-item v-if="form.ladderAuth == 0" label="批发价：" label-width="170px" prop="wholesalePrice">
              <el-input v-model="form.wholesalePrice"
                @keyup.native="form.wholesalePrice = checkInputNum(form.wholesalePrice)"
                class="short-input width-per-50">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </div>
          <!-- </template> -->

          <!-- 零售商品 -->
          <!-- <template v-if="fromListPage == 30"> -->
          <div v-if="fromListPage == 30">

            <!-- 零售价 -->
            <el-form-item label="零售价：" label-width="170px" prop="sellPrice">
              <el-input v-model="form.sellPrice"
                @keyup.native="form.sellPrice = checkInputNum(form.sellPrice)"
                class="short-input width-per-50"
                @blur="doChangeSellprice">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>

            <!-- 分销价 -->
            <el-form-item label="分销价：" label-width="170px" prop="distributePrice">
              <el-input v-model="form.distributePrice"
                @keyup.native="form.distributePrice = checkInputNum(form.distributePrice)"
                class="short-input width-per-50">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>

            <!-- 会员价 -->
            <el-form-item v-if="enterpriseConfig.memberPriceAuthority == 1" :label="memberTitle + '价：'" label-width="170px">
              <el-input v-model="form.memberPrice"
                @keyup.native="form.memberPrice = checkInputNum(form.memberPrice)"
                class="short-input width-per-50">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>

            <!-- 样品价 -->
            <el-form-item v-if="enterpriseConfig.anchorSelectionAuthority == '1'" label="样品价：" label-width="170px" prop="specimenPrice">
              <el-input v-model="form.specimenPrice"
                @keyup.native="form.specimenPrice = checkInputNum(form.specimenPrice)"
                class="short-input width-per-50">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>

          </div>
          <!-- </template> -->

          <!-- 非供货联盟商品 -->
          <template v-if="form.goodsSource !== '3'">

            <!-- 供应价 -->
            <el-form-item label="供应价：" label-width="170px">
              <el-input v-model="form.supplyPrice"
                @keyup.native="form.supplyPrice = checkInputNum(form.supplyPrice)"
                class="short-input width-per-50"
                :disabled="!enterpriseGoodsFlag">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>

            <!-- 供应商运费 -->
            <el-form-item label="供应商运费：" label-width="170px" v-if="form.goodsSource == '1'">
              <el-input v-model="form.supplierPostFee" class="short-input width-per-50" :disabled="true">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>

            <template v-if="enterpriseConfig.warehouseAuthority == 1 && enterpriseGoodsFlag">
              <!-- 供应价含税 -->
              <el-form-item label="供应价含税：" label-width="170px">
                <el-select v-model="form.supplierTaxFlag">
                  <el-option label="已含税" value="1"></el-option>
                  <el-option label="未含税" value="0"></el-option>
                </el-select>
              </el-form-item>
              <!-- 进项税税目 -->
              <el-form-item label="进项税税目：" label-width="170px">
                <el-select v-model="form.taxItemsId" clearable>
                  <el-option label="无" value=""></el-option>
                  <el-option v-for="item in taxList"
                    :key="item.taxItemsId"
                    :label="item.taxName + '(' + item.taxRate + '%)'"
                    :value="item.taxItemsId">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>

          </template>

          <!-- 商品库存 -->
          <el-form-item label="商品库存：" label-width="170px" prop="stock">
            <el-input v-model="form.stock"
              @keyup.native="form.stock = checkInputNumWithPoint(form.stock, 0)"
              class="long-input-2"
              :disabled="!stockEditFlag">
            </el-input>
          </el-form-item>

          <!-- 库存预警 -->
          <el-form-item label="库存预警：" label-width="170px">
            <el-input v-model="form.stockWarn"
              @keyup.native="form.stockWarn = checkInputNumWithPoint(form.stockWarn, 0)"
              class="long-input-2"
              :disabled="!stockEditFlag">
            </el-input>
            <div class="tips">商品库存少于预警数量，商品列表库存数量标红显示，库存为0自动下架</div>
          </el-form-item>

        </template>

        <!-- 运费设置 -->
        <div>
          <!-- 批发商品 -->
          <template v-if="fromListPage == 31">

            <!-- 配送方式 -->
            <el-form-item v-if="enterpriseConfig.deliveryTemplateAuthority == 1" label="配送方式：" label-width="170px">
              <el-select v-model="form.templateType" @change="doChangeTemplateType" class="width-200">
                <el-option label="快递" value="1"></el-option>
                <el-option label="物流" value="2"></el-option>
              </el-select>
            </el-form-item>

            <!-- 批发运费 -->
            <el-form-item  label="批发运费：" label-width="170px" prop="wholesalePostFeeType">
              <el-radio-group v-model="form.wholesalePostFeeType" class="freight-radio">
                <el-radio label="10">
                  <span>统一运费</span>
                  <el-input v-model="form.wholesalePostFee"
                    @keyup.native="form.wholesalePostFee = checkInputNum(form.wholesalePostFee)"
                    class="width-200 mar-l-20">
                    <template slot="append">元</template>
                  </el-input>
                </el-radio>
                <template v-if="enterpriseConfig.deliveryTemplateAuthority == 1 && form.goodsSource != 2">
                  <el-radio label="11">
                    <span>货号运费模板</span>
                    <el-select v-model="form.wholesaleDeliveryTemplateId" class="mar-l-20" clearable>
                      <el-option v-for="(item, index) in deliveryTemplates"
                        :key="index"
                        :label="item.templateName"
                        :value="item.templateId">
                      </el-option>
                    </el-select>
                    <el-button type="text" class="mar-l-20" @click.native="listDeliveryTemplate">刷新</el-button>
                    <el-button type="text" @click.native="goAddTemplate">新增运费模板</el-button>
                    <el-button type="text" @click.native="editTemplate(form.wholesaleDeliveryTemplateId)">编辑选中模版</el-button>
                  </el-radio>
                  <el-radio label="12" v-if="form.skuFlag == 1">
                    <span>SKU运费模板</span>
                  </el-radio>
                </template>
              </el-radio-group>
            </el-form-item>

          </template>
          <!-- 零售商品 -->
          <template v-if="fromListPage == 30">

            <!-- 零售运费 -->
            <el-form-item  label="零售运费：" label-width="170px" prop="postFeeType">
              <el-radio-group v-model="form.postFeeType" class="freight-radio">
                <el-radio label="10">
                  <span>统一运费</span>
                  <el-input v-model="form.postFee"
                    @keyup.native="form.postFee = checkInputNum(form.postFee)"
                    class="width-200 mar-l-20">
                    <template slot="append">元</template>
                  </el-input>
                </el-radio>
                <template v-if="enterpriseConfig.deliveryTemplateAuthority == 1 && form.goodsSource != 2">
                  <el-radio label="11">
                    <span>货号运费模板</span>
                    <el-select v-model="form.deliveryTemplateId" class="mar-l-20" clearable>
                      <el-option v-for="(item, index) in deliveryTemplates"
                        :key="index"
                        :label="item.templateName"
                        :value="item.templateId">
                      </el-option>
                    </el-select>
                    <el-button type="text" class="mar-l-20" @click.native="listDeliveryTemplate">刷新</el-button>
                    <el-button type="text" @click.native="goAddTemplate">新增运费模板</el-button>
                    <el-button type="text" @click.native="editTemplate(form.deliveryTemplateId)">编辑选中模版</el-button>
                  </el-radio>
                  <el-radio label="12" v-if="form.skuFlag == 1">
                    <span>SKU运费模板</span>
                  </el-radio>
                </template>
              </el-radio-group>
            </el-form-item>

            <!-- 分销运费 -->
            <el-form-item  label="分销运费：" label-width="170px" prop="distributePostFeeType">
              <el-radio-group v-model="form.distributePostFeeType" class="freight-radio">
                <el-radio label="10">
                  <span>统一运费</span>
                  <el-input v-model="form.distributePriceFee"
                    @keyup.native="form.distributePriceFee = checkInputNum(form.distributePriceFee)"
                    class="width-200 mar-l-20">
                    <template slot="append">元</template>
                  </el-input>
                </el-radio>
                <template v-if="enterpriseConfig.deliveryTemplateAuthority == 1 && form.goodsSource != 2">
                  <el-radio label="11">
                    <span>货号运费模板</span>
                    <el-select v-model="form.distributeDeliveryTemplateId" class="mar-l-20" clearable>
                      <el-option v-for="(item, index) in deliveryTemplates"
                        :key="index"
                        :label="item.templateName"
                        :value="item.templateId">
                      </el-option>
                    </el-select>
                    <el-button type="text" class="mar-l-20" @click.native="listDeliveryTemplate">刷新</el-button>
                    <el-button type="text" @click.native="goAddTemplate">新增运费模板</el-button>
                    <el-button type="text" @click.native="editTemplate(form.distributeDeliveryTemplateId)">编辑选中模版</el-button>
                  </el-radio>
                  <el-radio label="12" v-if="form.skuFlag == 1">
                    <span>SKU运费模板</span>
                  </el-radio>
                </template>
              </el-radio-group>
            </el-form-item>

          </template>
        </div>

        <!-- 多规格 -->
        <div v-show="form.skuFlag == 1">
          <!-- 规格块 -->
          <el-form-item label="商品规格：" v-if="propChangeFlag" label-width="170px">
            <div v-for="(item, index) in form.qualityData" :key="index" class="quality-bar mar-b-15">
              <div class="mar-b-20 position-r qta-item flex">
                <span class="flex-item">
                  <el-select v-model="item.skuPropName" placeholder="请选择" @change="(val) => doChangeQta(val, index)" ref="select">
                    <el-option v-for="item in skuPropList"
                      :key="item.skuPropName"
                      :label="item.skuPropName"
                      :value="item.skuPropName"
                      :disabled="item.disabled">
                    </el-option>
                    <el-option style="padding: 0" value="">
                      <el-button style="width: 100%; border: none; " icon="el-icon-plus" @click="addSku">添加主规格</el-button>
                    </el-option>
                  </el-select>
                </span>
                <i class="el-icon-error font-26 close-quality" @click="removeQta(item, index)"></i>
              </div>
              <el-row :gutter="20" class="pad-l-30 pad-r-30">
                <el-col :span="8" v-for="(subItem, subIndex) in item.skuPropValueList" :key="subIndex" class="flex v-align-c mar-b-10">
                  <span class="flex-item mar-r-10 position-r">
                    <el-input v-model="subItem.skuPropValue" class="width-per-100" placeholder="子规格名称（比如：红色）"></el-input>
                    <i class="el-icon-error close-sub" @click="removeSubQta(item.skuPropValueList, subIndex)"></i>
                  </span>
                  <template v-if="(subIndex + 1 == item.skuPropValueList.length)">
                    <span class="font-14 font-blue" @click="addSubQta(item)">添加子规格</span>
                  </template>
                </el-col>
              </el-row>
            </div>
            <div>
              <el-button type="primary" size="small" @click="addQta">添加规格</el-button>
            </div>
          </el-form-item>

          <!-- sku列表 -->
          <el-form-item label="商品sku：" label-width="170px" prop="skuTemp">
            <div class="table-container pad-b-10">
              <div class="el-table el-table--fit el-table--border el-table--enable-row-hover el-table--medium el-table--scrollable-x">
                <div class="el-table__body-wrapper">
                  <table cellspacing="0" cellpadding="0" border="0" class="el-table__body" style="width: 100%">
                    <!-- sku表头 -->
                    <thead class="el-table__header">
                      <tr>
                        <!-- 规格信息 -->
                        <template v-if="form.goodsSource == 2">
                          <th width="120">
                            <div class="cell text-align-c">规格</div>
                          </th>
                        </template>
                        <template v-else>
                          <template v-for="(item, indexTh) in form.qualityData">
                            <th width="120" :key="'indexTh-' + indexTh">
                              <div class="cell text-align-c">{{ item.skuPropName }}</div>
                            </th>
                          </template>
                        </template>

                        <!-- 图片 -->
                        <th width="100">
                          <div class="cell text-align-c">图片</div>
                        </th>
                        <!-- 划线价 -->
                        <th width="135">
                          <div class="cell text-align-c">
                            <span>划线价(元)</span>
                            <batch-set field="scribingPrice" inputType="number" @confirmed="doCallbackBatchSet"></batch-set>
                          </div>
                        </th>
                        <!-- 供货联盟商品 -->
                        <template v-if="form.goodsSource === '3'">
                          <!-- 联盟供应价 -->
                          <th width="145">
                            <div class="cell text-align-c">联盟供应价(元)</div>
                          </th>
                          <!-- 联盟零售价 -->
                          <th width="125">
                            <div class="cell text-align-c">
                              <label slot="reference">
                                <span>联盟零售价(元)</span>
                              </label>
                            </div>
                          </th>
                          <!-- 联盟批发价 -->
                          <th width="125">
                            <div class="cell text-align-c">
                              <label slot="reference">
                                <span>联盟批发价(元)</span>
                              </label>
                            </div>
                          </th>
                        </template>
                        <template v-else>
                          <!-- 供应价 -->
                          <th width="135">
                            <div class="cell text-align-c">
                              <span>供应价(元)</span>
                              <batch-set field="supplyPrice" inputType="number" @confirmed="doCallbackBatchSet"></batch-set>
                            </div>
                          </th>
                        </template>
                        <!-- 批发商品 -->
                        <template v-if="fromListPage === 31">
                          <!-- 批发价 -->
                          <th width="135" v-if="form.ladderAuth == 0">
                            <div class="cell text-align-c">
                              <span>批发价</span>
                              <span v-if="form.supplyAllianceWholesalePriceType !== 2">
                                <batch-set field="wholesalePrice" inputType="number" @confirmed="doCallbackBatchSet"></batch-set>
                              </span>
                            </div>
                          </th>
                          <!-- 批发运费模板 -->
                          <th width="135" v-if="form.wholesalePostFeeType == 12">
                            <div class="cell text-align-c">
                              <span>批发运费模板</span>
                              <batch-set field="wholesaleDeliveryTemplateId" inputType="select" :templates="deliveryTemplates" @confirmed="doCallbackBatchSet"></batch-set>
                            </div>
                          </th>
                        </template>
                        <!-- 零售商品 -->
                        <template v-else>
                          <!-- 零售价 -->
                          <th width="135">
                            <div class="cell text-align-c">
                              <span>零售价(元)</span>
                              <batch-set field="sellPrice" inputType="number" @confirmed="doCallbackBatchSet"></batch-set>
                            </div>
                          </th>
                          <!-- 分销价 -->
                          <th width="135">
                            <div class="cell text-align-c">
                              <span>分销价(元)</span>
                              <batch-set field="distributePrice" inputType="number" @confirmed="doCallbackBatchSet"></batch-set>
                            </div>
                          </th>
                          <!-- 会员价 -->
                          <th v-if="enterpriseConfig.memberPriceAuthority == 1" width="135">
                            <div class="cell text-align-c">
                              <span>{{ memberTitle }}价(元)</span>
                              <batch-set field="memberPrice" inputType="number" @confirmed="doCallbackBatchSet"></batch-set>
                            </div>
                          </th>
                          <!-- 样品价 “主播选品”增值功能开启时显示 -->
                          <th width="135" v-if="enterpriseConfig.anchorSelectionAuthority == '1'">
                            <div class="cell text-align-c">
                              <span>样品价(元)</span>
                              <batch-set field="specimenPrice" inputType="number" @confirmed="doCallbackBatchSet"></batch-set>
                            </div>
                          </th>
                          <!-- 零售运费模板 -->
                          <th width="135" v-if="form.postFeeType == 12">
                            <div class="cell text-align-c">
                              <span>零售运费模板</span>
                              <batch-set field="deliveryTemplateId" inputType="select" :templates="deliveryTemplates" @confirmed="doCallbackBatchSet"></batch-set>
                            </div>
                          </th>
                          <!-- 分销运费模板 -->
                          <th width="135" v-if="form.distributePostFeeType == 12">
                            <div class="cell text-align-c">
                              <span>分销运费模板</span>
                              <batch-set field="distributeDeliveryTemplateId" inputType="select" :templates="deliveryTemplates" @confirmed="doCallbackBatchSet"></batch-set>
                            </div>
                          </th>
                        </template>
                        <!-- 库存 -->
                        <th width="135">
                          <div class="cell text-align-c">
                            <span>库存</span>
                            <batch-set v-if="stockEditFlag" field="stock" inputType="int" @confirmed="doCallbackBatchSet"></batch-set>
                          </div>
                        </th>
                        <!-- 库存预警 -->
                        <th width="135">
                          <div class="cell text-align-c">
                            <span>库存预警</span>
                            <batch-set v-if="stockEditFlag" field="warnStock" inputType="int" @confirmed="doCallbackBatchSet"></batch-set>
                          </div>
                        </th>
                        <!-- 条形码 -->
                        <th width="135">
                          <div class="cell text-align-c">
                            <span>条形码</span>
                            <batch-set field="goodsBarCode" inputType="string" @confirmed="doCallbackBatchSet"></batch-set>
                          </div>
                        </th>
                        <!-- 外部编码 -->
                        <th width="135">
                          <div class="cell text-align-c" v-if="externalCodeConfigForm.contentType == undefined || externalCodeConfigForm.contentType == 1 || externalCodeConfigForm.contentType == 2">
                            外部编码
                          </div>
                          <div v-else class="cell text-align-c">
                            <el-popover placement="top" width="160" v-model="visiblePopExternalCode">
                              <div class="text-align-c pad-b-10">批量设置</div>
                              <el-form label-position="right" style="width: 100%">
                                <el-form-item>
                                  <el-input v-if="externalCodeConfigForm.contentType == 4" placeholder="系统随机生成"
                                    :disabled="true" />
                                  <el-input v-if="externalCodeConfigForm.contentType == 3" placeholder="请输入自定义内容"
                                    v-model="externalCodeConfigForm.customizeContent" />
                                </el-form-item>
                              </el-form>
                              <div class="mar-t--10" style="text-align: right">
                                <el-button size="mini" type="text" @click="visiblePopExternalCode = false">取消</el-button>
                                <el-button type="primary" size="mini" @click="generateExternalCode()">确定</el-button>
                              </div>
                              <label slot="reference">
                                <span>外部编码</span>
                                <i class="el-icon-circle-plus mar-l-10 font-blue"></i>
                              </label>
                            </el-popover>
                          </div>
                        </th>
                      </tr>
                    </thead>
                    <!-- sku列表 -->
                    <tbody>
                      <tr v-for="(item, index) in form.qualityTable" :key="'info-' + index">
                        <!-- 规格信息 -->
                        <template v-if="form.goodsSource == 2">
                          <td>
                            <div class="cell">
                              <span>{{ item.skuDetail }}</span>
                            </div>
                          </td>
                        </template>
                        <template v-else>
                          <template v-for="(subItem, subIndex) in item.skuPropValueList">
                            <template v-if="subItem.skuPropId">
                              <td :key="subIndex">
                                <div class="cell text-align-c">
                                  {{ subItem.skuPropValue }}
                                </div>
                              </td>
                            </template>
                          </template>
                        </template>

                        <!-- 图片 -->
                        <td>
                          <div class="cell text-align-c">
                            <el-upload list-type="picture-mini"
                              action="/api/common/uploadFiles"
                              accept="image/jpeg,image/gif,image/png,image/bmp"
                              name="files"
                              v-loading="item.picLoading"
                              :data="token"
                              :show-file-list="false"
                              :on-success="(res, file, fileList) => handleUploadSuccess(res, file, fileList, item)"
                              :before-upload="(file) => beforeUpload(file, item)"
                            >
                              <img v-if="item.imageUrl" :src="item.imageUrl" width="38px" height="38px"/>
                              <i v-else class="el-icon-plus"></i>
                            </el-upload>
                          </div>
                        </td>
                        <!-- 划线价 -->
                        <td>
                          <div class="cell">
                            <el-input v-model="item.scribingPrice"
                              @keyup.native="item.scribingPrice = checkInputNum(item.scribingPrice)">
                            </el-input>
                          </div>
                        </td>
                        <!-- 供货联盟商品 -->
                        <template v-if="form.goodsSource === '3'">
                          <!-- 联盟供应价 -->
                          <td>
                            <div style="text-align: center" class="cell">
                              <span>{{ item.supplyAlliancePrice ? item.supplyAlliancePrice : '--' }}</span>
                            </div>
                          </td>
                          <!-- 联盟零售价 -->
                          <td>
                            <div class="cell" style="text-align: center">
                              <span v-if="item.supplyAllianceSellMinPrice">
                                <span v-if="item.supplyAllianceSellMinPrice  === item.supplyAllianceSellMaxPrice">
                                  {{item.supplyAllianceSellMinPrice}}
                                </span>
                                <span v-else>
                                  <span v-if="item.supplyAllianceSellMaxPrice !== null">
                                    {{item.supplyAllianceSellMinPrice}}--{{item.supplyAllianceSellMaxPrice}}
                                  </span>
                                </span>
                              </span>
                              <span v-else>--</span>
                            </div>
                          </td>
                          <!-- 联盟批发价 -->
                          <td>
                            <div class="cell" style="text-align: center">
                              <span v-if="item.supplyAllianceMinWholesalePrice">
                                <span v-if="item.supplyAllianceMinWholesalePrice  === item.supplyAllianceMaxWholesalePrice">
                                  {{item.supplyAllianceMinWholesalePrice}}
                                </span>
                                <span v-else>
                                  <span v-if="item.supplyAllianceMaxWholesalePrice !== null">
                                    {{item.supplyAllianceMinWholesalePrice}}--{{item.supplyAllianceMaxWholesalePrice}}
                                  </span>
                                </span>
                              </span>
                              <span v-else>--</span>
                            </div>
                          </td>
                        </template>
                        <template v-else>
                          <!-- 供应价 -->
                          <th width="135">
                            <div class="cell">
                              <el-input v-model="item.supplyPrice"
                                @keyup.native="item.supplyPrice = checkInputNum(item.supplyPrice)">
                              </el-input>
                            </div>
                          </th>
                        </template>
                        <!-- 批发商品 -->
                        <template v-if="fromListPage === 31">
                          <!-- 批发价 -->
                          <td v-if="form.ladderAuth == 0">
                            <div class="cell">
                              <el-input v-model="item.wholesalePrice"
                                @keyup.native="item.wholesalePrice = checkInputNum(item.wholesalePrice)">
                              </el-input>
                            </div>
                          </td>
                          <!-- 批发运费模板 -->
                          <td v-if="form.wholesalePostFeeType == 12">
                            <div class="cell">
                              <el-select v-model="item.wholesaleDeliveryTemplateId" clearable>
                                <el-option v-for="(item, index) in deliveryTemplates"
                                  :key="index"
                                  :label="item.templateName"
                                  :value="item.templateId">
                                </el-option>
                              </el-select>
                            </div>
                          </td>
                        </template>
                        <!-- 零售商品 -->
                        <template v-else>
                          <!-- 零售价 -->
                          <td>
                            <div class="cell">
                              <el-input v-model="item.price"
                                @keyup.native="item.price = checkInputNum(item.price)"
                                @blur="doChangeSellprice">
                              </el-input>
                            </div>
                          </td>
                          <!-- 分销价 -->
                          <td>
                            <div class="cell">
                              <el-input v-model="item.distributePrice"
                                @keyup.native="item.distributePrice = checkInputNum(item.distributePrice)">
                              </el-input>
                            </div>
                          </td>
                          <!-- 会员价 -->
                          <td v-if="enterpriseConfig.memberPriceAuthority == 1">
                            <div class="cell">
                              <el-input v-model="item.memberPrice"
                                @keyup.native="item.memberPrice = checkInputNum(item.memberPrice)">
                              </el-input>
                            </div>
                          </td>
                          <!-- 样品价 “主播选品”增值功能开启时显示 -->
                          <td v-if="enterpriseConfig.anchorSelectionAuthority == '1'">
                            <div class="cell">
                              <el-input v-model="item.specimenPrice"
                                @keyup.native=" item.specimenPrice = checkInputNum(item.specimenPrice)">
                              </el-input>
                            </div>
                          </td>
                          <!-- 零售运费模板 -->
                          <td v-if="form.postFeeType == 12">
                            <div class="cell">
                              <el-select v-model="item.deliveryTemplateId" clearable>
                                <el-option v-for="(item, index) in deliveryTemplates"
                                  :key="index"
                                  :label="item.templateName"
                                  :value="item.templateId">
                                </el-option>
                              </el-select>
                            </div>
                          </td>
                          <!-- 分销运费模板 -->
                          <td v-if="form.distributePostFeeType == 12">
                            <div class="cell">
                              <el-select v-model="item.distributeDeliveryTemplateId" clearable>
                                <el-option v-for="(item, index) in deliveryTemplates"
                                  :key="index"
                                  :label="item.templateName"
                                  :value="item.templateId">
                                </el-option>
                              </el-select>
                            </div>
                          </td>
                        </template>
                        <!-- 库存 -->
                        <td>
                          <div class="cell">
                            <el-input v-model="item.stock"
                              @keyup.native="item.stock = checkInputNum(item.stock)"
                              :disabled="!stockEditFlag">
                            </el-input>
                          </div>
                        </td>
                        <!-- 库存预警 -->
                        <td>
                          <div class="cell">
                            <el-input v-model="item.warnStock"
                              @keyup.native="item.warnStock = checkInputNum(item.warnStock)"
                              :disabled="!stockEditFlag">
                            </el-input>
                          </div>
                        </td>
                        <!-- 条形码 -->
                        <td>
                          <div class="cell">
                            <el-input v-model="item.goodsBarCode" placeholder="请输入条形码"></el-input>
                          </div>
                        </td>
                        <!-- 外部编码 -->
                        <td>
                          <div class="cell">
                            <el-input v-model="item.externalCode" :disabled="form.goodsSource === '3'" placeholder="请输入外部编码"></el-input>
                          </div>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>

            <!-- 验证显示用 -->
            <el-form-item label="商品sku：" label-width="0px" class="not-show" prop="skuList">
            </el-form-item>
          </el-form-item>
        </div>

      </el-form-item>
    </el-form>

    <!-- 阶梯批发设置 -->
    <el-drawer :visible.sync="ladderVisible" :wrapperClosable="false" :close-on-press-escape="false" direction="rtl" size="620px">
      <ladder-wholesale-price
      :form="form"
      @callback="doCallbackLadderPrice">
      </ladder-wholesale-price>
    </el-drawer>

  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  // import { listCategorySku } from '@/api/goods/goods'
  import { listTemplate } from '@/api/sell/delivery-template.js'
  import { getTaxList } from '@/api/warehouse/warehouseTaxItems'
  import { getExternalCodeConfig, saveExternalCodeConfig } from '@/api/user/externalCodeConfig'

  import batchSet from './components/batch-set'
  import ladderWholesalePrice from './components/ladder-wholesale-price'
  import goodsBus from '@/views/goods/edit/goods-bus'
  import goodsSkuFormCheck from './goods-sku-form-check'

  export default {
    mixins: [goodsBus, goodsSkuFormCheck],
    components: { batchSet, ladderWholesalePrice },
    props: {
      // 跳转源 30：零售 31：批发
      fromListPage: {
        type: Number,
        default: 30
      },
      // 商品对象
      goodsObj: {
        type: Object
      }
    },
    data() {
      // 零售价规则
      const sellPriceRule = (rule, value, callback) => {
        const errorMsg = this.sellPriceCheck(
          this.form.sellPrice,
          this.form.goodsSource,
          this.form.supplyAllianceSellMinPrice,
          this.form.supplyAllianceSellMaxPrice,
          this.form.supplyAllianceSellPriceType
        )
        if (errorMsg) {
          return callback(new Error(errorMsg))
        }
        return callback()
      }
      // 样品价规则
      const specimenPriceRule = (rule, value, callback) => {
        const errorMsg = this.specimenCheck(
          this.form.specimenPrice,
          this.form.selectionGoodsType,
          this.form.goodsSource,
          this.form.supplyAllianceSellMinPrice,
          this.form.supplyAllianceSellMaxPrice,
          this.form.supplyAllianceSellPriceType
        )
        if (errorMsg) {
          return callback(new Error(errorMsg))
        }
        return callback()
      }
      // 零售运费规则
      const postFeeTypeRule = (rule, value, callback) => {
        const errorMsg = this.postFeeTypeCheck(
          this.form.postFeeType,
          this.form.postFee,
          this.form.deliveryTemplateId
        )
        if (errorMsg) {
          return callback(new Error(errorMsg))
        }
        return callback()
      }
      // 分销运费规则
      const distributePostFeeTypeRule = (rule, value, callback) => {
        const errorMsg = this.distributePostFeeTypeCheck(
          this.form.distributePostFeeType,
          this.form.distributePriceFee,
          this.form.distributeDeliveryTemplateId
        )
        if (errorMsg) {
          return callback(new Error(errorMsg))
        }
        return callback()
      }
      // 批发运费规则
      const wholesalePostFeeTypeRule = (rule, value, callback) => {
        const errorMsg = this.wholesalePostFeeTypeCheck(
          this.form.wholesalePostFeeType,
          this.form.wholesalePostFee,
          this.form.wholesaleDeliveryTemplateId
        )
        if (errorMsg) {
          return callback(new Error(errorMsg))
        }
        return callback()
      }
      // 阶梯批发规则
      const ladderAuthRule = (rule, value, callback) => {
        if (this.form.ladderAuth === '1' && this.form.ladderPriceList.length === 0) {
          return callback(new Error('请设置阶梯批发价'))
        }
        callback()
      }
      // sku模板规则
      const skuTempRule = (rule, value, callback) => {
        this.$refs['form'].validateField('skuList')
        callback()
      }
      // sku列表规则
      const skuListRule = (rule, value, callback) => {
        if (this.form.skuFlag === '1') {
          const errorMsgArr = []
          this.form.qualityTable.forEach(item => {
            if (errorMsgArr.length > 0) return

            if (this.fromListPage === 30) {
              const errorMsg_price = this.sellPriceCheck(
                item.price,
                this.form.goodsSource,
                item.supplyAllianceSellMinPrice,
                item.supplyAllianceSellMaxPrice,
                this.form.supplyAllianceSellPriceType
              )
              if (errorMsg_price) {
                errorMsgArr.push(errorMsg_price)
              }

              const errorMsg_specimen = this.specimenCheck(
                item.specimenPrice,
                this.form.selectionGoodsType,
                this.form.goodsSource,
                item.supplyAllianceSellMinPrice,
                item.supplyAllianceSellMaxPrice,
                this.form.supplyAllianceSellPriceType
              )
              if (errorMsg_specimen) {
                errorMsgArr.push(errorMsg_specimen)
              }

              const errorMsg_postFeeType = (this.form.postFeeType === '12' && !item.deliveryTemplateId) ? '请选择零售运费模板' : ''
              if (errorMsg_postFeeType) {
                errorMsgArr.push(errorMsg_postFeeType)
              }

              const errorMsg_distributePostFeeType = (this.form.distributePostFeeType === '12' && !item.distributeDeliveryTemplateId) ? '请选择分销运费模板' : ''
              if (errorMsg_distributePostFeeType) {
                errorMsgArr.push(errorMsg_distributePostFeeType)
              }
            } else {
              // const errorMsg_wholesalePrice = (this.form.ladderAuth === '0' && Number.isNaN(parseFloat(item.wholesalePrice))) ? '请输入批发价' : ''
              if (this.form.ladderAuth === '0') {
                const errorMsg_wholesalePrice = this.wholesalePriceCheck(
                  item.wholesalePrice,
                  this.form.goodsSource,
                  item.supplyAllianceMinWholesalePrice,
                  item.supplyAllianceMaxWholesalePrice,
                  this.form.supplyAllianceWholesalePriceType,
                  this.form.supplyAllianceIsEnableWholesaleModel
                )
                if (errorMsg_wholesalePrice) {
                  errorMsgArr.push(errorMsg_wholesalePrice)
                }
              }

              const errorMsg_wholesalePostFeeType = (this.form.wholesalePostFeeType === '12' && !item.wholesaleDeliveryTemplateId) ? '请选择批发运费模板' : ''
              if (errorMsg_wholesalePostFeeType) {
                errorMsgArr.push(errorMsg_wholesalePostFeeType)
              }
            }

            const errorMsg_stock = Number.isNaN(parseFloat(item.stock)) ? '请输入库存' : ''
            if (errorMsg_stock) {
              errorMsgArr.push(errorMsg_stock)
            }
          })

          if (errorMsgArr.length > 0) {
            return callback(new Error(errorMsgArr.join('，')))
          }
        }
        callback()
      }
      // 批发价规则
      const wholesalePriceRule = (rule, value, callback) => {
        const errorMsg = this.wholesalePriceCheck(
          this.form.wholesalePrice,
          this.form.goodsSource,
          this.form.supplyAllianceMinWholesalePrice,
          this.form.supplyAllianceMaxWholesalePrice,
          this.form.supplyAllianceWholesalePriceType,
          this.form.supplyAllianceIsEnableWholesaleModel
        )
        if (errorMsg) {
          return callback(new Error(errorMsg))
        }
        return callback()
      }
      return {
        token: {},
        // 规格改变计数（监听用）
        propChangeCount: 0,
        // 表单
        form: {
          goodsId: '',
          goodsSource: '0',
          ladderAuth: '0',
          selectionGoodsType: 0, // 选品小程序
          skuFlag: '0',
          stock: '0',
          stockWarn: '',
          goodsBarCode: '', // 商品条形码
          externalCode: '', // 外部编码
          memberPrice: '',
          sellPrice: '',
          // 分销价
          distributePrice: '',
          // 样品价
          specimenPrice: '',
          supplyPrice: '',
          scribingPrice: '',
          wholesalePrice: '',
          deliveryTemplateId: '',
          distributeDeliveryTemplateId: '',
          wholesaleDeliveryTemplateId: '',
          wholesaleNum: '',
          postFeeType: '10',
          distributePostFeeType: '10',
          postFee: 0,
          distributePriceFee: 0,
          // 配送方式 1：快递 2：物流
          templateType: '1',
          wholesalePostFeeType: '10',
          wholesalePostFee: 0,
          supplierPostFee: '',
          supplyAlliancePrice: '',
          supplyAllianceSellPriceType: '',
          supplyAllianceSellMinPrice: '',
          supplyAllianceSellMaxPrice: '',
          ladderPriceList: [], // 阶梯批发价
          qualityData: [{
            skuPropId: -1,
            skuPropName: '',
            categoryId: '',
            skuPropValueList: [{
              skuPropValue: '',
              skuPropValueId: -2,
              skuPropId: -1,
              skuPropName: ''
            }]
          }],
          qualityTable: [],
          // 供应价含税
          supplierTaxFlag: '1',
          taxItemsId: '',
          // 跨境类型：1-普通商品，2-跨境保税
          crossBorderType: '1',
          // 批发价模式
          supplyAllianceIsEnableWholesaleModel: '',
          supplyAllianceWholesalePriceType: '',
          supplyAllianceMaxWholesalePrice: '',
          supplyAllianceMinWholesalePrice: ''
        },
        // 外部编码表单
        externalCodeConfigForm: {},
        // 运费模板列表
        deliveryTemplates: [],
        descartesTable: [],
        ids: [],
        // 阶梯批发visible
        ladderVisible: false,
        // 批量设置主播结算价
        visiblePopExternalCode: false,
        // 表单规则
        rules: {
          skuFlag: [
            { required: true, trigger: 'change', message: '请选择规格类型' }
          ],
          wholesalePrice: [
            { required: true, trigger: 'blur', message: '请输入批发价' },
            { trigger: 'blur', validator: wholesalePriceRule }
          ],
          wholesaleNum: [
            { required: true, trigger: 'blur', message: '请输入起批数量' }
          ],
          ladderAuth: [
            { required: true, trigger: 'change', validator: ladderAuthRule }
          ],
          sellPrice: [
            { required: true, trigger: 'blur', message: '请输入零售价' },
            { trigger: 'blur', validator: sellPriceRule }
          ],
          specimenPrice: [
            { trigger: 'blur', validator: specimenPriceRule }
          ],
          wholesalePostFeeType: [
            { required: true, trigger: 'change', validator: wholesalePostFeeTypeRule }
          ],
          postFeeType: [
            { required: true, trigger: 'change', validator: postFeeTypeRule }
          ],
          distributePostFeeType: [
            { required: true, trigger: 'change', validator: distributePostFeeTypeRule }
          ],
          stock: [
            { required: true, trigger: 'blur', message: '请输入商品库存' }
          ],
          skuTemp: [
            { trigger: 'blur', validator: skuTempRule }
          ],
          skuList: [
            { trigger: 'blur', validator: skuListRule }
          ]
        },
        // 数据字典
        dict: {
          skuFlag: {}
        },
        categoryId: '',
        // 规格列表
        skuPropList: [],
        // 企业配置
        enterpriseConfig: {
          deliveryTemplateAuthority: 0,
          anchorSelectionAuthority: 0
        },
        // 税目列表
        taxList: [],
        // 企业商品flag
        enterpriseGoodsFlag: true,
        // 规格修改flag true：可 false：不可
        propChangeFlag: true,
        // 库存编辑flag true：可 false：不可
        stockEditFlag: true,
        // sku修改flag true：可 false：不可
        skuChangeFlag: true,
        memberTitle: '会员',
        // 初始化sku信息
        skuInitForm: {
          imageUrl: '',
          price: '',
          specimenPrice: '', // 样品价
          memberPrice: '', // 会员价
          supplyAllianceSellMinPrice: '',
          supplyAllianceSellMaxPrice: '',
          supplyAlliancePrice: '',
          distributePrice: '', // 分销价
          scribingPrice: '', // 划线价
          wholesalePrice: '', // 批发价
          goodsBarCode: '', // 条形码
          deliveryTemplateId: '', // 零售运费模板
          wholesaleDeliveryTemplateId: '', // 批发运费模板
          distributeDeliveryTemplateId: '', // 分销运费模板
          externalCode: '', // 外部编码
          supplyPrice: '', // 供应价
          stock: '0', // 库存
          warnStock: '' // 库存预警
        }
      }
    },
    // 初始化页面
    created() {
      this.token = { accessToken: getToken() }
      listTemplate({
        enterpriseId: this.getEnterpriseId(),
        templateType: this.form.templateType
      }).then(response => {
        this.deliveryTemplates = response.data
      })
      // 获取税目信息
      getTaxList(this.getEnterpriseId()).then(response => {
        if (response.isError) return
        this.taxList = response.data
      })
      this.getExternalCodeConfig()
    },
    mounted() {
      const goodsBaseData = this.$store.state.goodsBaseData
      Object.assign(this.enterpriseConfig, goodsBaseData.enterpriseConfig)
      Object.assign(this.dict, goodsBaseData.dict)
      this.initForm()

      const that = this
      // 监听事件
      that.bindChangeCrossBorderType(function(value) {
        that.form.crossBorderType = value
        // 开启仓库库存，不允许编辑
        const warehouseDeliverFlag = that.enterpriseConfig.warehouseAuthority === 1 && that.enterpriseConfig.warehouseDeliverFlag === 1
        // 库存编辑flag 【未开启仓库发货】且【总部自营】且【普通商品】
        that.stockEditFlag = !warehouseDeliverFlag && that.form.goodsSource === '0' && that.form.crossBorderType === '1'
      })
      that.bindSelectionGoodsType(function(value) {
        that.form.selectionGoodsType = value
      })

      // this.qualityInit()

      // const that = this

      // this.$bus.$on('goods.edit.categoryId', function(categoryId) {
      //   that.categoryId = categoryId
      //   that.categoryChange()
      // })
    },
    watch: {
      // 标记已选规格
      propChangeCount() {
        const selectedPropList = []
        this.form.qualityData.forEach(item => {
          selectedPropList.push(item.skuPropName)
        })
        this.skuPropList.forEach(item => {
          if (selectedPropList.indexOf(item.skuPropName) === -1) {
            item.disabled = false
          } else {
            item.disabled = true
          }
        })
      }
    },
    methods: {
      // 初始化表单
      initForm() {
        if (this.goodsObj.goodsId || this.goodsObj.goodsSyncHistoryId) {
          Object.assign(this.form, this.goodsObj)
          this.form.skuFlag = this.form.skuFlag.toString()
          this.form.postFeeType = this.form.postFeeType.toString()
          this.form.wholesalePostFeeType = this.form.wholesalePostFeeType.toString()
          this.form.distributePostFeeType = this.form.distributePostFeeType.toString()
          this.form.templateType = this.form.templateType.toString()
          this.form.supplierTaxFlag = this.form.supplierTaxFlag.toString()
          this.form.crossBorderType = this.form.crossBorderType.toString()
          this.form.goodsSource = this.form.goodsSource.toString()
          this.form.ladderAuth = this.form.ladderAuth.toString()
          if (this.form.skuFlag === '1') {
            if (this.form.goodsSource !== '2') {
              // 构造skuPropValueList
              const skuPropValueMap = new Map()
              this.form.qualityData.forEach(item => {
                item.skuPropValueList.forEach(item_v => {
                  skuPropValueMap.set(item_v.skuPropValueId, item_v)
                })
              })
              this.form.qualityTable.forEach(item => {
                const skuPropValueList = []
                const skuValueIds = item.skuValueIds.split(',')
                skuValueIds.forEach(skuValueId => skuPropValueList.push(skuPropValueMap.get(skuValueId)))
                item.skuPropValueList = skuPropValueList
                this.initSKuValue(item, item)
              })
            }
          }
          this.listDeliveryTemplate()
          this.$nextTick(() => {
            this.doChangeSellprice()
          })
        } else {
          this.qualityInit()
        }
        if (!this.form.taxItemsId) {
          // 设置默认进项税税目
          this.form.taxItemsId = this.enterpriseConfig.taxItemsId
        }
        this.memberTitle = this.enterpriseConfig.memberTitle || '会员'

        // 企业商品flag
        this.enterpriseGoodsFlag = this.form.goodsSource === '0'
        // 开启仓库库存，不允许编辑
        const warehouseDeliverFlag = this.enterpriseConfig.warehouseAuthority === 1 && this.enterpriseConfig.warehouseDeliverFlag === 1
        // 库存编辑flag 【未开启仓库发货】且【总部自营】且【普通商品】
        this.stockEditFlag = !warehouseDeliverFlag && this.form.goodsSource === '0' && this.form.crossBorderType === '1'
        // 规格修改flag 【新建商品】或（【未开启仓库发货】且【总部商品】）
        this.propChangeFlag = !this.form.goodsId || (!warehouseDeliverFlag && this.form.goodsSource === '0')
        // sku修改flag 【新建商品】
        this.skuChangeFlag = !this.form.goodsId
      },
      // 跳转到新增运费模板页
      goAddTemplate() {
        const routeData = this.$router.resolve({
          path: '/order/order/express/delivery-template-detail/index',
          query: {}
        })
        window.open(routeData.href, '_blank')
      },
      // 编辑运费模板
      editTemplate(templateId) {
        const routeData = this.$router.resolve({
          path: '/order/order/express/delivery-template-detail/index',
          query: {
            templateId: templateId
          }
        })
        window.open(routeData.href, '_blank')
      },
      // 添加一级规格
      addQta() {
        const propId = this.getID()
        const valueId = this.getID()
        this.form.qualityData.push({
          // categoryId: '',
          skuPropId: propId,
          skuPropName: '',
          skuPropValueList: [{
            skuPropValue: '',
            skuPropValueId: valueId,
            skuPropId: propId,
            skuPropName: ''
          }]
        })
        this.qualityInit()
      },
      // 添加规格事件
      addSku() {
        this.$prompt('请输入规格', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValidator: (value) => {
            if (!value) {
              return '请输入规格'
            }
            if (value.replace(/\s/g, '').length !== value.length) {
              return '不能有空格'
            }
            if (value.length > 10) {
              return '做多输入10个字符'
            }
            return true
          }
        }).then(({ value }) => {
          const date = {
            skuPropName: value
          }
          this.skuPropList.push(date)
        }).catch(() => {
          this.$message({ type: 'info', message: '取消输入' })
        })
      },
      // 规格选择事件
      doChangeQta(propName, index) {
        this.propChangeCount++
        const skuProp = this.form.qualityData[index]
        skuProp.skuPropId = this.getID()
        skuProp.skuPropValueList.forEach(skuPropValue => {
          skuPropValue.skuPropId = skuProp.skuPropId
          skuPropValue.skuPropName = skuProp.skuPropName
          skuPropValue.skuPropValueId = this.getID()
        })
      },
      // 删除一级规格
      removeQta(item, index) {
        if (this.form.qualityData.length > 1) {
          this.$confirm('此操作将删除该规格，是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.propChangeCount++
            this.form.qualityData.splice(index, 1)
            this.qualityInit()
          })
        }
      },
      // 删除子规格
      removeSubQta(item, subIndex) {
        if (item.length <= 1) {
          return
        }
        item.splice(subIndex, 1)
        this.qualityInit()
      },
      // 添加子规格
      addSubQta(item) {
        const valueId = this.getID()
        const data = {
          skuPropValue: '',
          skuPropValueId: valueId,
          skuPropId: '',
          skuPropName: ''
        }
        item.skuPropValueList.push(data)
        this.qualityInit()
      },
      // 数列展示
      qualityInit() {
        if (this.form.qualityData.length === 0) {
          this.addQta()
          return
        }

        // 规格值列表 设置规格id 规格名称，并返回笛卡尔积
        const arrQta = []
        this.form.qualityData.forEach(item => {
          const skuPropId = item.skuPropId
          const skuPropName = item.skuPropName
          item.skuPropValueList.forEach(item_v => {
            item_v.skuPropId = skuPropId
            item_v.skuPropName = skuPropName
          })
          arrQta.push(item.skuPropValueList)
        })
        this.descartesTable = this.$utils.descartes(arrQta)

        // 规格变化前后 键值对
        const beforeValueMap = new Map()
        const afterValueMap = new Map()

        this.form.qualityTable.forEach(item => {
          const skuPropValueIds = item.skuPropValueList.map(prop => prop.skuPropValueId)
          beforeValueMap.set(skuPropValueIds.sort().toString(), item)
        })

        this.descartesTable.forEach(item => {
          let skuPropValueIds
          if (Array.isArray(item)) {
            skuPropValueIds = item.map(prop => prop.skuPropValueId)
          } else {
            skuPropValueIds = [item.skuPropValueId]
          }
          afterValueMap.set(skuPropValueIds.sort().toString(), item)
        })

        // 变化前键值
        const beforeValueKeys = []
        for (const key of beforeValueMap.keys()) {
          beforeValueKeys.push(key)
        }
        const beforeValueKeyLength = beforeValueMap.size === 0 ? 0 : beforeValueMap.keys().next().value.split(',').length
        const afterValueKeyLength = afterValueMap.keys().next().value.split(',').length
        const lengthGap = beforeValueKeyLength - afterValueKeyLength

        const skuList = []
        afterValueMap.forEach((v, k) => {
          let beforeValue
          if (lengthGap === 0) {
            beforeValue = beforeValueMap.get(k)
          } else {
            const afterKeys = k.split(',')
            const keyCount = afterKeys.length
            const keys = beforeValueKeys.filter(item => {
              const matchCount = afterKeys.filter(a_k => item.indexOf(a_k) !== -1).length
              return matchCount === (lengthGap > 0 ? keyCount : keyCount - 1)
            })
            beforeValue = keys.length === 0 ? null : beforeValueMap.get(keys[0])
          }
          // 初始化行信息
          const obj = {}
          this.initSKuValue(obj, beforeValue)
          obj.skuPropValueList = Array.isArray(v) ? v : [v]
          skuList.push(obj)
        })

        this.form.qualityTable = skuList
        this.descartesTable = []
      },
      // 初始化行信息
      initSKuValue(obj, val) {
        this.$set(obj, 'imageUrl', (val && val.imageUrl) ? val.imageUrl : '')
        this.$set(obj, 'price', (val && val.price) ? val.price : '')
        // 样品价
        this.$set(obj, 'specimenPrice', (val && val.specimenPrice) ? val.specimenPrice : '')
        // 会员价
        this.$set(obj, 'memberPrice', (val && val.memberPrice) ? val.memberPrice : '')
        this.$set(obj, 'supplyAllianceSellMinPrice', (val && val.supplyAllianceSellMinPrice) ? val.supplyAllianceSellMinPrice : '')
        this.$set(obj, 'supplyAllianceSellMaxPrice', (val && val.supplyAllianceSellMaxPrice) ? val.supplyAllianceSellMaxPrice : '')
        this.$set(obj, 'supplyAlliancePrice', (val && val.supplyAlliancePrice) ? val.supplyAlliancePrice : '')
        // 分销价
        this.$set(obj, 'distributePrice', (val && val.distributePrice) ? val.distributePrice : '')
        // 划线价
        this.$set(obj, 'scribingPrice', (val && val.scribingPrice) ? val.scribingPrice : '')
        // 批发价
        this.$set(obj, 'wholesalePrice', (val && val.wholesalePrice) ? val.wholesalePrice : '')
        // 条形码
        this.$set(obj, 'goodsBarCode', (val && val.goodsBarCode) ? val.goodsBarCode : '')
        // 零售运费模板
        this.$set(obj, 'deliveryTemplateId', (val && val.deliveryTemplateId) ? val.deliveryTemplateId : '')
        // 批发运费模板
        this.$set(obj, 'wholesaleDeliveryTemplateId', (val && val.wholesaleDeliveryTemplateId) ? val.wholesaleDeliveryTemplateId : '')
        // 分销运费模板
        this.$set(obj, 'distributeDeliveryTemplateId', (val && val.distributeDeliveryTemplateId) ? val.distributeDeliveryTemplateId : '')
        // 外部编码
        this.$set(obj, 'externalCode', (val && val.externalCode) ? val.externalCode : '')
        // 供应价
        this.$set(obj, 'supplyPrice', (val && val.supplyPrice) ? val.supplyPrice : '')
        // 库存
        this.$set(obj, 'stock', (val && val.stock) ? val.stock : '0')
        // 库存预警
        this.$set(obj, 'warnStock', (val && val.warnStock) ? val.warnStock : '')
      },
      // categoryChange() {
      //   listCategorySku(this.categoryId).then((response) => {
      //     if (response.isError) return
      //     this.skuPropList = response.data
      //   })
      // },
      getID(length) {
        const ids = this.ids
        const id = -parseInt(Math.round(Math.random() * 100000000))
        if (ids.indexOf(id) > 0) {
          this.getID()
        } else {
          ids.push(id)
          this.ids = ids
          return id
        }
      },
      // 图片上传前校验
      beforeUpload(file, item) {
        const isJPG = file.type === 'image/jpeg'
        const isGIF = file.type === 'image/gif'
        const isPNG = file.type === 'image/png'
        const isBMP = file.type === 'image/bmp'
        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
          return
        }
        this.$set(item, 'picLoading', true)
        return isJPG || isBMP || isGIF || isPNG
      },
      // 图片上传成功后处理
      handleUploadSuccess(res, file, fileList, item) {
        item.picLoading = false
        if (res.code === 101) {
          item.imageUrl = res.data[0]
        } else {
          this.$message({ type: 'error', message: res.msg })
        }
      },
      // 批量设置回调
      doCallbackBatchSet(field, value) {
        this.form.qualityTable.forEach(item => {
          switch (field) {
            // 划线价
            case 'scribingPrice':
              item.scribingPrice = value
              break
            // 供应价
            case 'supplyPrice':
              item.supplyPrice = value
              break
            // 零售价
            case 'sellPrice':
              item.price = value
              break
            // 分销价
            case 'distributePrice':
              item.distributePrice = value
              break
            // 会员价
            case 'memberPrice':
              item.memberPrice = value
              break
            // 样品价
            case 'specimenPrice':
              item.specimenPrice = value
              break
            // 批发价
            case 'wholesalePrice':
              item.wholesalePrice = value
              break
            // 库存
            case 'stock':
              item.stock = value
              break
            // 库存预警
            case 'warnStock':
              item.warnStock = value
              break
            // 条形码
            case 'goodsBarCode':
              item.goodsBarCode = value
              break
            // 零售运费模板
            case 'deliveryTemplateId':
              item.deliveryTemplateId = value
              break
            // 批发运费模板
            case 'wholesaleDeliveryTemplateId':
              item.wholesaleDeliveryTemplateId = value
              break
            // 分销运费模板
            case 'distributeDeliveryTemplateId':
              item.distributeDeliveryTemplateId = value
              break
          }
        })
        if (field === 'sellPrice') {
          this.$nextTick(() => {
            this.doChangeSellprice()
          })
        }
      },
      // 阶梯批发价回调
      doCallbackLadderPrice(priceList) {
        if (priceList) {
          this.form.ladderPriceList = priceList
          this.$nextTick(() => this.checkForm('ladderAuth'))
        }
        this.ladderVisible = false
      },
      // 零售价修改事件
      doChangeSellprice() {
        let price
        if (this.form.skuFlag === '0') {
          price = this.form.sellPrice
        } else {
          let priceArr = this.form.qualityTable.map(item => item.price)
          priceArr = priceArr.sort((a, b) => b - a)
          price = priceArr[0]
        }
        this.emitChangeSellPrice(price)
      },
      // 物流方式切换事件
      doChangeTemplateType() {
        if (this.fromListPage === 31) {
          this.form.wholesaleDeliveryTemplateId = ''
          this.listDeliveryTemplate()
        }
      },
      listDeliveryTemplate() {
        listTemplate({
          enterpriseId: this.getEnterpriseId(),
          templateType: this.form.templateType
        }).then(response => {
          this.deliveryTemplates = response.data
        })
      },
      // 获取企业外部编码配置
      getExternalCodeConfig() {
        getExternalCodeConfig(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          if (response.data !== undefined) {
            this.externalCodeConfigForm = response.data
          }
        })
      },
      // 规格类型修改事件
      doChangeSkuFlag() {
        this.doChangeSellprice()
      },
      // 生成外部编码
      generateExternalCode() {
        // 系统随机和自定义才可点击生成
        if (this.externalCodeConfigForm.contentType === 3) {
          if (!this.externalCodeConfigForm.customizeContent) {
            this.$message({
              type: 'error',
              message: '自定义内容不能为空'
            })
            return
          } else {
            // 保存自定义文本
            saveExternalCodeConfig(this.externalCodeConfigForm).then(response => {
              if (response.isError) return
              this.visiblePopExternalCode = false
            })
          }
        } else {
          this.visiblePopExternalCode = false
        }
      },
      // 表单校验 true：成功 false：失败
      checkForm(prop) {
        let ret = true
        let checkArrays = []
        if (prop) {
          checkArrays = Array.isArray(prop) ? prop : [prop]
        } else {
          this.$refs['form'].fields.forEach(field => {
            if (field.prop === 'skuTemp') {
              return
            }
            checkArrays.push(field.prop)
          })
        }
        this.$refs['form'].validateField(checkArrays, (errorMsg, result) => {
          if (errorMsg) {
            const propKeys = Object.keys(result)
            this.$refs['form'].fields.forEach(field => {
              const index = propKeys.indexOf(field.prop)
              if (index !== -1) {
                this.$emit('addVaildShow', field)
              }
            })
            ret = false
          }
        })
        return ret
      },
      // 提交表单
      submitForm() {
        // sku列表
        const skuList = []
        this.form.qualityTable.forEach(item => {
          const skuObj = {
            skuId: item.skuId, // skuId
            imageUrl: item.imageUrl, // 图片
            price: item.price, // 零售价
            memberPrice: item.memberPrice, // 会员价
            distributePrice: item.distributePrice, // 分销价
            specimenPrice: item.specimenPrice, // 样品价
            scribingPrice: item.scribingPrice, // 划线价
            wholesalePrice: item.wholesalePrice, // 批发价
            goodsBarCode: item.goodsBarCode, // 条形码
            externalCode: item.externalCode, // 外部编码
            supplyPrice: item.supplyPrice, // 供应价
            warnStock: item.warnStock, // 库存预警
            stock: item.stock, // 库存
            deliveryTemplateId: item.deliveryTemplateId, // 零售运费模板id
            wholesaleDeliveryTemplateId: item.wholesaleDeliveryTemplateId, // 批发运费模板id
            distributeDeliveryTemplateId: item.distributeDeliveryTemplateId, // 分销运费模板id
            skuPropValueList: item.skuPropValueList // 规格值列表
          }
          skuList.push(skuObj)
        })

        const submitForm = {
          skuFlag: this.form.skuFlag, // 规格类型
          supplyPrice: this.form.supplyPrice, // 供应价
          supplierTaxFlag: this.form.supplierTaxFlag, // 供应价是否含税 1:已含税 0：未含税（默认）
          taxItemsId: this.form.taxItemsId, // 进项税税目
          stock: this.form.stock, // 库存
          stockWarn: this.form.stockWarn, // 库存预警
          goodsBarCode: this.form.goodsBarCode, // 条形码
          externalCode: this.form.externalCode, // 外部编码

          sellPrice: this.form.sellPrice, // 零售价
          scribingPrice: this.form.scribingPrice, // 划线价
          memberPrice: this.form.memberPrice, // 会员价
          specimenPrice: this.form.specimenPrice, // 样品价
          distributePrice: this.form.distributePrice, // 分销价
          distributePriceFee: this.form.distributePriceFee, // 分销运费
          distributePostFeeType: this.form.distributePostFeeType, // 分销运费类型 10：统一运费 11：货号运费模板 12：SKU运费模板
          distributeDeliveryTemplateId: this.form.distributeDeliveryTemplateId, // 分销运费模板id
          templateType: this.form.templateType, // 配送方式 1.快递 2.物流

          postFee: this.form.postFee, // 零售运费
          postFeeType: this.form.postFeeType, // 零售运费类型 10：统一运费 11：货号运费模板 12：SKU运费模板
          deliveryTemplateId: this.form.deliveryTemplateId, // 零售运费模板id

          wholesalePrice: this.form.wholesalePrice, // 批发价
          wholesaleNum: this.form.wholesaleNum, // 起批数
          wholesalePostFee: this.form.wholesalePostFee, // 批发运费
          wholesalePostFeeType: this.form.wholesalePostFeeType, // 批发运费类型 10：统一运费 11：货号运费模板 12：SKU运费模板
          wholesaleDeliveryTemplateId: this.form.wholesaleDeliveryTemplateId, // 批发运费模板id

          ladderAuth: this.form.ladderAuth, // 阶梯批发权限 0关闭 1开启
          ladderPriceList: this.form.ladderPriceList, // 阶梯批发集合

          qualityData: this.form.qualityData, // 规格信息
          qualityTable: skuList // sku列表
        }
        return submitForm
      }
    }
  }
</script>


<style lang="less" scoped>
  .table-container {
    min-height: auto;
  }
  .freight-radio {
    /deep/.el-radio {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
    }
    /deep/.el-radio__label {
      display: flex;
      align-items: center;
    }
  }

  .quality-bar {
    background: #f2f2f2;
    border: #e4e4e4 1px solid;
    padding: 10px;

    .close-quality {
      color: #515151;
    }

    .close-sub {
      color: #aeaeae;
      position: absolute;
      right: -6px;
      top: -6px;
      font-size: 18px;
    }

    .qta-item:before {
      content: '';
      position: absolute;
      left: 12px;
      top: 34px;
      width: 1px;
      height: 46px;
      background: #bcbcbc;
    }

    .qta-item:after {
      content: '';
      position: absolute;
      left: 12px;
      top: 79px;
      width: 19px;
      height: 1px;
      background: #bcbcbc;
    }
  }

  .span-bar {
    padding: 0 50px;
  }

  .remove-btn {
    padding: 7px 6px !important;
  }

  .long-input {
    width: 80%;
  }

  .long-input-2 {
    width: 55%;
    margin-right: 5%;
  }

  .long-input-3 {
    width: 55%;
  }

  .short-input {
    width: 20%;
  }

  .short-input-2 {
    width: 25%;
  }

  .default-input {
    width: 80%;

    @media screen and (max-width: 1440px) {
      width: 100%;
    }
  }

  .tips {
    color: gray;
    font-size: 12px;
    line-height: 1.2;
    padding-top: 5px;
  }

  .picture {
    width: 130px;
    height: 130px;
    display: block;
  }
  .input-bar-0 {
    width: 35% !important;
  }

  .input-bar-1 {
    width: 40%;
    margin-bottom: 5px !important;
  }

  .input-bar-2 {
    width: 60%;
    margin-bottom: 5px !important;
  }

  .input-bar-3 {
    width: 100%;
    margin-bottom: 5px !important;
  }

  .input-bar-4 {
    width: 35% !important;
  }

  .width-input-1 {
    width: 100% !important;
  }

  .width-input-2 {
    width: 35% !important;
  }

  .width-input-3 {
    width: 30% !important;
  }

  .width-date {
    width: 200px !important;
  }

  .gray-bar {
    background: #fff;
    padding: 5px 0 0 0;
    margin-bottom: 20px;
  }

  .gray-active {
    margin-right: 20px;
    // padding: 15px 13px;

    &.active {
      background: #fff;
    }
  }

  .noraml-height {
    height: 40px;
  }
  /deep/ .not-show label {
    display: none;
  }
</style>
